var argv=process.argv;
var bindhost=argv[2];
var bindport=argv[3];
var net=require('net');
var firadio=require('firnode');
var client_serverc={};
//===================================
process.title='TCP服务器测试端['+bindport+']';
var stdin=process.openStdin();
stdin.setEncoding('binary');
stdin.on('data',function(chunk){
    var chunk_len=chunk.length-2;
    chunk=firadio.gbk_to_utf8(chunk.substr(0,chunk_len));
    if(chunk=='exit'){
        process.exit();
    }
    process.stdout.write('data:['+chunk+']('+chunk_len+")\r\n");
    client_serverc.write(chunk);
});
stdin.on('end',function(){
    process.stdout.write('end');
});
//===================================
var server=net.createServer(function(serverc){
    var remoteAddress=serverc.remoteAddress;//来自IP地址
    var remotePort=serverc.remotePort;//来自端口号
    var ip_and_port=remoteAddress+':'+remotePort;
    var conndatetime=+new Date();
    client_serverc=serverc;
    firadio.log('来自['+ip_and_port+']进来了！');
    serverc.on('close',function(){
        firadio.log('走了['+ip_and_port+']断开！');
    });
    serverc.on('data',function(data){
        firadio.log('来自['+ip_and_port+']发来数据！  length:'+data.length);
        firadio.log(''+data.toString());
    });
});
server.on('error',function(data){
    var errorinfo=data.toString();
    if(errorinfo=='Error: listen EADDRINUSE'){
        errorinfo='监听端口被占用！';
    }
    firadio.log('TCP服务器有错误：'+errorinfo);
    process.exit();
});
server.listen(bindport,bindhost,function(){
    firadio.log('TCP服务器已启动！');
});
